package com.lemon.core.common.lang.util;

import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lottery
 * @ClassName FileUtils
 * @desc 文件工具类
 * @Date 2018/11/3 21:25
 * @Version 1.0
 **/
public class FileUtils {

    public static final String UTF_8 = "UTF-8";

    public static boolean exists(String filePath) {
        return new File(filePath).exists();
    }

    public static String getFileContent(String filePath) {
        if (!exists(filePath)) {
            return null;
        }
        return readFileContent(new File(filePath));
    }

    private static String readFileContent(File file) {
        StringBuffer fileContent = new StringBuffer();
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(new FileInputStream(file), UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String lineTxt = null;
            while ((lineTxt = br.readLine()) != null) {
                fileContent.append(lineTxt);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileContent.toString();
    }

    /**
     * 获取文件夹所有子文件数量
     * @param file
     * @param size
     */
    public static void getChildFileSize(File file, AtomicInteger size) {
        File[] childFiles = file.listFiles();
        for (File childFile : childFiles) {
            if (childFile.isDirectory()) {
                getChildFileSize(childFile, size);
            } else {
                size.incrementAndGet();
            }
        }
    }
}
